package org.yangjie;

import java.io.FileOutputStream;
import java.math.BigInteger;
import java.util.List;
import java.util.Objects;

import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableCell.XWPFVertAlign;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;

public class TableDemo {
	
	public static void main(String[] args) throws Exception{
		XWPFDocument document = new XWPFDocument();
		// 创建表格
		XWPFTable table = document.createTable(2, 8);
		table.setWidth(Units.toEMU(100));
		XWPFTableRow row = table.getRow(0);
		row.getCell(0).setText("1");
		row.getCell(1).setText("2");
		row.getCell(2).setText("3");
		row.getCell(3).setText("4");
		row.getCell(4).setText("5");
		row.getCell(5).setText("6");
		row.getCell(6).setText("总分");
		row.getCell(7).setText("计分人");
		formatTable(table);

		document.write(new FileOutputStream("d:/1.docx"));
		document.close();
		
	}

	/**
	 * 设置表格格式
	 * @param table
	 */
	private static void formatTable(XWPFTable table) {
		List<XWPFTableRow> rowList = table.getRows();
		if (Objects.nonNull(rowList) && !rowList.isEmpty()) {
			for(XWPFTableRow row : rowList){
				row.setHeight(400); //高度
				List<XWPFTableCell> cellList = row.getTableCells();
				if(Objects.nonNull(cellList) && !cellList.isEmpty()){
					for(XWPFTableCell cell : cellList){
				        CTTcPr cellPr = cell.getCTTc().addNewTcPr();
			            cellPr.addNewTcW().setW(BigInteger.valueOf(700));
						cell.setVerticalAlignment(XWPFVertAlign.CENTER); // 垂直居中
						cell.getParagraphs().get(0).setAlignment(ParagraphAlignment.CENTER); // 水平居中
					}
				}
			}
		}
	}

}
